package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.core.utils.JsonUtils;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author MJJ
 * @date 2025-06-05
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Integer id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        // 设置参数
        listProductsRequest.setLimit(50);
        // 发起请求
        ListProductsResponse listProductsResponse = client.listProducts(listProductsRequest);
        if (listProductsResponse.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }

        // 存储到redis中
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(listProductsResponse.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.判断设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getId())
                .count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }

        //2.判断设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId())
                .count();
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }

        //如果位置类型是0，设置物理位置为-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }


        //3.判断同一位置是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            log.error("同一位置已绑定相同产品");
            throw new BaseException("同一位置已绑定相同产品");
        }

        //4.注册iot设备
        //随机生成密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");

        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice
                .withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey())
                .withNodeId(deviceDto.getNodeId())
                .withAuthInfo(new AuthInfo()
                        .withSecret(secret));

        addDeviceRequest.withBody(addDevice);
        AddDeviceResponse response;
        response = client.addDevice(addDeviceRequest);
    /*    try {
            response = client.addDevice(addDeviceRequest);
        } catch (Exception e) {
            log.error("设备注册失败", e);
            throw new BaseException("设备注册失败");
        }*/

        //5.保存设备信息

        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        save(device);
    }


    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {

        //去数据库查询设备信息
        Device device = lambdaQuery().eq(Device::getIotId, iotId)
                .one();
        if (device == null){
            return null;
        }
        //调用华为云接口查询设备详情
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(showDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        //属性拷贝
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());

        String activeTimeStr = response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;

    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest showDeviceShadowRequest = new ShowDeviceShadowRequest();
        showDeviceShadowRequest.setDeviceId(iotId);
        ShowDeviceShadowResponse showDeviceShadowResponse = client.showDeviceShadow(showDeviceShadowRequest);
        if (showDeviceShadowResponse.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = showDeviceShadowResponse.getShadow();
        if(CollUtil.isEmpty(shadow)){
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        List<Map<String,Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);
    }

    @Override
    public void editDevice(DeviceDto deviceDto) {
        Device device = getById(deviceDto.getId());
        if (device == null){
            throw new BaseException("设备不存在");
        }
        if(device.getLocationType() != deviceDto.getLocationType()){
            throw new BaseException("设备位置类型不能修改");
        }


        //更新物联网设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request = request.withDeviceId(device.getIotId());
        UpdateDevice updateBody  = new UpdateDevice();
        updateBody.withDeviceName(deviceDto.getDeviceName());
        request.withBody(updateBody);
        try {
            client.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 更新设备信息，调用失败");
        }

        //更新数据库
        BeanUtil.copyProperties(deviceDto,device);
        Long count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .ne(Device::getId, device.getId())
                .count();
        if (count > 0) {
            log.error("该位置已绑定相同产品");
            throw new BaseException("该位置已绑定相同产品");
        }
        updateById(device);
    }

    /**
     * 删除设备
     */
    @Override
    public void deleteDevice(String iotIds) {

        //删除华为云设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotIds);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            new BaseException("物联网接口 - 删除设备，调用失败");
        }
        //删除数据库
        Device device = lambdaQuery().eq(Device::getIotId, iotIds).one();
        removeById(device);
    }
    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {

        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }

        //调用华为云物联网接口
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = null;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }

        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }


        return AjaxResult.success(serviceCapabilities);

    }
}
